<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="queryParams" label-width="80px">
      <el-form-item label="礼物名称">
        <el-input
          v-model="queryParams.giftName"
          clearable
          placeholder="请输入礼物名称"
        />
      </el-form-item>
      <!-- 礼物状态：自动回显 -->
      <el-form-item label="礼物状态">
        <el-select
          v-model="queryParams.status"
          clearable
          placeholder="请选择礼物状态"
          style="width: 120px"
        >
          <el-option label="全部" value="" />
          <el-option label="已上架" value="on" />
          <el-option label="已下架" value="off" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增按钮 -->
    <div class="mb8">
      <el-button type="primary" icon="Plus" @click="openAddDialog">
        新增礼物
      </el-button>
    </div>

    <!-- 表格区域：flex-grow 占满剩余高度 -->
    <div class="table-wrapper">
      <el-table :data="tableData" v-loading="loading" height="100%">
        <el-table-column type="index" width="60" label="序号" fixed="left" />
        <el-table-column label="图片" width="150" fixed="left">
          <template #default="{ row }">
            <el-avatar :src="row.giftImg" shape="square" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="giftName" label="礼物名称" min-width="200" />
        <el-table-column prop="price" label="金币" width="100" />
        <!-- Switch 状态（文字内置 + 居中表头） -->
        <el-table-column label="状态" width="200" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'0'"
              :inactive-value="'1'"
              active-text="上架"
              inactive-text="下架"
              @change="toggleStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="220" />
        <!-- 操作列：居中 + 二次确认 -->
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <div class="nowrap-operation">
              <el-button size="small" type="primary" @click="openForm(row)">
                <Edit style="width: 14px" />
                编辑
              </el-button>
              <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <!-- 新增 / 编辑弹窗：Switch 控制状态 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="450px"
      append-to-body
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="礼物名称" prop="giftName">
          <el-input v-model="form.giftName" placeholder="请输入礼物名称" />
        </el-form-item>
        <el-form-item label="金币" prop="price">
          <el-input-number
            v-model="form.price"
            :min="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            active-value="0"
            inactive-value="1"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
        <el-form-item label="礼物图片" prop="giftImg">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="uploadImage"
          >
            <img v-if="form.giftImg" :src="form.giftImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Plus } from '@element-plus/icons-vue'
import { Gift, GiftResponse } from '@/api/gifts/type'
import {
  R,
  page,
  PageQuery,
  emptyPageInfo,
  ResponseData,
  PageInfo,
} from '@/api/common/type'
import {
  reqGiftsPage,
  reqGiftsAdd,
  reqGiftsOne,
  reqGiftsDel,
  reqGiftsUpdate,
} from '@/api/gifts/index'

type GiftStatus = 'on' | 'off'


/* ========== 搜索 ========== */
const queryParams = reactive({
  giftName: '',
  status: '',
  dateRange: [],
  pageNum: 1,
  pageSize: 10,
})
const loading = ref(false)
const total = ref(0)
const tableData = ref<Gift[]>([])

/* ========== 表单 ========== */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  id: undefined as number | undefined,
  giftName: '',
  price: 1,
  status: '0' as GiftStatus,
  giftImg: '',
})
const rules = {
  giftName: [{ required: true, message: '请输入礼物名称', trigger: 'blur' }],
  coin: [{ required: true, message: '请输入金币数', trigger: 'blur' }],
  image: [{ required: true, message: '请上传图片', trigger: 'change' }],
}

/* ========== 列表 + 分页 ========== */
const handleQuery = async () => {
  loading.value = true

  const pageInfo: PageInfo = {
    pageSize: queryParams.pageSize,
    pageIndex: queryParams.pageNum,
  }

  const gift: Gift = { ...queryParams }

  if (queryParams.dateRange.length > 1) {
    gift.beginTime = queryParams.dateRange[0] + 'T00:00:00'
    gift.endTime = queryParams.dateRange[1] + 'T23:59:59'
  }

  const query: PageQuery<Gift> = {
    filterData: gift,
    pageInfo: pageInfo,
  }

  const result: GiftResponse = await reqGiftsPage(query)

  if (result && result.code === 200) {
    tableData.value = result.data.records
    total.value = result.data.total
  } else {
    return Promise.reject(new Error(result.message))
  }
  loading.value = false
}
function resetQuery() {
  Object.assign(queryParams, {
    giftName: '',
    status: '',
    dateRange: [],
    pageNum: 1,
  })
  handleQuery()
}

/* ========== 表单操作 ========== */

// 打开添加对话框
const openAddDialog = () => {
  Object.assign(form, {})
  dialogVisible.value = true
}

function openForm(row?: Gift) {
  dialogTitle.value = row ? '编辑礼物' : '新增礼物'
  if (row) Object.assign(form, row)
  else resetForm()
  dialogVisible.value = true
}

function resetForm() {
  Object.assign(form, {
    id: undefined,
    giftName: '',
    price: 1,
    status: '0',
    image: '',
  })
}
const submitForm = async () => {
  formRef.value?.validate((valid: any) => {
    if (!valid) {
      return
    }
  })

  let g: Gift = { ...form }
  let result: R<boolean>

  if (g.giftId) {
    // 更新
    result = await reqGiftsUpdate(g)
  } else {
    result = await reqGiftsAdd(g)
  }

  if (result && result.code === 200) {
    dialogVisible.value = false

    if (g.giftId) {
      // 2. 取最新数据
      const { data: fresh } = await reqGiftsOne(g.giftId)
      // 3. 局部替换：只更新 giftId 匹配的那一行
      tableData.value = tableData.value.map((item) =>
        item.giftId === fresh.giftId ? fresh : item,
      )
    } else {
      handleQuery()
    }
  } else {
    ElMessage.success(g.giftId ? '礼物更新失败' : '礼物添加失败')
    return
  }
  ElMessage.success(g.giftId ? '礼物更新成功' : '礼物添加成功')
}
const handleDelete = async (row: Gift) => {
  
  await ElMessageBox.confirm('确定要删除该礼物吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

  console.log('row ====', row)

  const result: R<boolean> = await reqGiftsDel(row.giftId)

  if (result && result.success) {
    handleQuery()
    ElMessage.success('删除成功')
  } else {
    ElMessage.success('删除失败')
  }
}


const toggleStatus = async (row: Gift) => {
  await reqGiftsUpdate(row)

}

/* 图片上传（本地预览） */
function beforeUpload(file: File) {
  // const isImg = file.type.startsWith('image/')
  // if (!isImg) ElMessage.error('只能上传图片')
  // return isImg
}
function uploadImage({ file }: { file: File }) {
  // const reader = new FileReader()
  // reader.onload = () => (form.image = reader.result as string)
  // reader.readAsDataURL(file)
}

onMounted(handleQuery)
</script>

<style scoped>
/* 占满屏幕高度 */
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
}
.table-wrapper {
  flex: 1;
  overflow: hidden;
}
.nowrap-operation {
  display: flex;
  gap: 4px;
}
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
}
.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
  line-height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}
</style>
